<?php

namespace app\home\controller;

use think\Request;
use think\Db;
use think\Session;
use think\Controller;
use mlsmt\Cabinet\Send;

/**
 * Charecabinet Controller
 */
class Charecabinet extends Common
{
    /**
     * 机柜列表
     */
    public function index()
    {
        $userInfo = $this->getLoginUserInfo();

//        $pageNum = Request::instance()->get('page_num', 1);
//        $pageSize = Request::instance()->get('page_size', 10);
        $sid = Request::instance()->get('id');

        $where = [
            'charecabinet.is_delete' => 1,
            'sid' => $sid
        ];

        $charecabinets = Db::name('charecabinet')
            ->field(['charecabinet.*', 'seller.name', 'seller.id as seller_id'])
            ->join('seller', [
                'charecabinet.sid=seller.id'
            ])
            ->where($where)
//            ->limit(($pageNum - 1) * $pageSize, $pageSize)
            ->order('id', 'desc')
            ->select();

        foreach ($charecabinets as &$item) {
            $item = $this->formatInfo($item);
        }

        return $this->fetch('index', [
            'charecabinets' => $charecabinets,
            'seller_id' => $sid
        ]);
    }

    /**
     * 设备管理
     */
    public function manage()
    {
        $userInfo = $this->getLoginUserInfo();

//        $pageNum = Request::instance()->get('page_num', 1);
//        $pageSize = Request::instance()->get('page_size', 10);
        $cabinetId = Request::instance()->post('cabinet_id');
        $sid = Request::instance()->post('sid');
        $status = Request::instance()->post('status');

        $where = [
            'aid' => $userInfo['session_id'],
            'is_delete' => 1
        ];

        if (!empty($sid)) {
            $where['sid'] = $sid;
        }
        if (!empty($cabinetId)) {
            $where['cabinet_id'] = $cabinetId;
        }
        if (!empty($status)) {
            $where['status'] = $status;
        }

        $charecabinets = Db::name('charecabinet')
            ->where($where)
//            ->limit(($pageNum - 1) * $pageSize, $pageSize)
            ->order('id', 'desc')
            ->select();

        foreach ($charecabinets as &$item) {
            $item = $this->formatInfo($item);
        }

        $sellers = Db::name('seller')
            ->where([
                'agency' => $userInfo['session_id'],
                'is_delete' => 1
            ])
            ->order('id', 'desc')
            ->select();

        return $this->fetch('manage', [
            'charecabinets' => $charecabinets,
            'sellers' => $sellers
        ]);
    }

    /**
     * 删除机柜
     *
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete()
    {
        $id = Request::instance()->get('id');
        $sid = Request::instance()->get('sid');

        Db::name('charecabinet')->where([
            'id' => $id
        ])->update([
            'is_delete' => 0
        ]);

        if ($sid) {
            $this->redirect(\think\Request::instance()->root().'/home/Charecabinet/index?id=' . $sid);
        } else {
            $this->redirect(\think\Request::instance()->root().'/home/Charecabinet/manage');
        }
    }

    /**
     * 详情页面
     */
    public function detail()
    {
        $id = Request::instance()->get('id');
        $charecabinet = Db::name('charecabinet')->where([
            'id' => $id
        ])->find();

        switch ($charecabinet['status']) {
            case 0:
                $charecabinet['status'] = '损坏';
                break;
            case 1:
                $charecabinet['status'] = '正常';
                break;
            case 2:
                $charecabinet['status'] = '测试';
                break;
            case 3:
                $charecabinet['status'] = '异常';
                break;
        }

        switch ($charecabinet['mode']) {
            case 1:
                $charecabinet['mode'] = '运营';
                break;
            case 2:
                $charecabinet['status'] = '调试';
                break;
        }

        $charecabinet['surplus'] = $this->getSurplus($charecabinet['cabinet_id']);

        $charecabinet['create_time'] = date('Y-m-d H:i:s', $charecabinet['create_time']);

        return $this->fetch('detail', [
            'charecabinet' => $charecabinet,
        ]);
    }

    /**
     * 绑定机柜页面
     */
    public function bindPage()
    {
        $userInfo = $this->getLoginUserInfo();

        $sid = input('sid');
        $charecabinets = Db::name('charecabinet')->where([
            'is_delete' => 1,
            'sid' => 0,
            'aid' => $userInfo['session_id']
        ])->order('id', 'desc')
            ->select();

        return $this->fetch('binding', [
            'charecabinets' => $charecabinets,
            'sid' => $sid
        ]);
    }

    /**
     * 绑定机柜
     */
    public function bind()
    {
        $id = input('id');
        $sid = input('sid');
        if (empty($id) || empty($sid)) {
            $this->exit_msg_callback('backFunc', '参数错误！');
        }

        $charecabinet = Db::name('charecabinet')->where([
            'id' => $id,
        ])->find();

        if ($charecabinet['sid'] > 0) {
            $this->exit_msg_callback('backFunc', '机柜已绑定！');
        }

        Db::name('charecabinet')->where([
            'id' => $id,
        ])->update([
            'sid' => $sid
        ]);

        $this->exit_msg_callback('backFunc', '绑定成功！', 1);
    }

    /**
     * 添加机柜页面
     */
    public function addPage()
    {
        return $this->fetch('add', []);
    }

    /**
     * 添加机柜操作
     */
    public function add()
    {
        $cabinetId = input('cabinet_id');
        if (empty($cabinetId)) {
            $this->exit_msg_callback('backFunc', '请输入机柜ID！');
        }
        $card = input('networking_card');
        if (empty($card)) {
            $this->exit_msg_callback('backFunc', '请输入互联网卡号！');
        }
        $model = input('model');
        if (empty($model)) {
            $this->exit_msg_callback('backFunc', '请输入机柜型号！');
        }
        $devicenum = input('devicenum');
        if (empty($devicenum)) {
            $this->exit_msg_callback('backFunc', '请选择可容纳充电宝数量！');
        }

        $userInfo = $this->getLoginUserInfo();

        $data = [
            'cabinet_id' => $cabinetId,
            'model' => $model,
            'networking_card' => $card,
            'devicenum' => $devicenum,
            'aid' => $userInfo['session_id'],
            'create_time' => $_SERVER['REQUEST_TIME']
        ];

        $sellerName = input('seller');
        if (!empty($sellerName)) {
            $seller = Db::name('seller')->field('id')->where([
                'name' => $sellerName,
                'agency' => $userInfo['session_id'],
                'is_delete' => 1,
            ])->find();

            if (!$seller) {
                $this->exit_msg_callback('backFunc', '商户不存在！');
            }

            $data['sid'] = $seller['id'];
        }

        Db::name('charecabinet')->insert($data);

        $this->exit_msg_callback('backFunc', '添加成功！', 1);
    }

    /**
     * 查询剩余充电宝数量
     *
     * @param string $cabinet_id
     * @return int
     */
    public function getSurplus($cabinet_id = '')
    {
        $Send = new Send($cabinet_id);
        $totals = $Send->StockNum();//获取总库存量
        isset($totals['info']) ? $total = $totals['info'] : $total = '';
        isset($totals['types']) ? $type = $totals['types'] : $type = '';

        if ($type) {
            return $total;
        }

        return 0;
    }

    /**
     * 格式化信息
     *
     * @param $item
     * @return array
     * @throws
     */
    public function formatInfo($item)
    {
//        $item['surplus'] = $this->getSurplus($item['cabinet_id']);
        $item['surplus'] = 0;

        switch ($item['status']) {
            case 0:
                $item['status'] = '损坏';
                break;
            case 1:
                $item['status'] = '正常';
                break;
            case 2:
                $item['status'] = '测试';
                break;
            case 3:
                $item['status'] = '异常';
                break;
        }

        $item['name'] = '';
        $seller = Db::name('seller')
            ->where(['id' => $item['sid']])
            ->find();

        if ($seller) {
            $item['name'] = $seller['name'];
        }

        return $item;
    }
}

